
(function($, window, document, undefined) {
    /*
     *dependecy:jqueryui
     */
    var pluginName = 'datagridform',
            defaults = {
                url: '',
                dialogConfirmText: '',
                dialogConfirmTitle: '',
                dialogConfirmButtonsText: {
                    cancel: 'Cancelar',
                    confirm: 'Cofirmar'
                },
                urlFile: '',
                langFile: 'pt_BR',
                modalFile: true,
                widthBoxFile: '90%',
                heightBoxFile: 500,
                callbackCompleteForm: function() {
                }
            };

    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.initialize();

    }
    Plugin.prototype = {
        url: '',
        data: {},
        isAjax: true,
        dataType: 'json',
        initialize: function() {
            var self = this;




            $(this.element).on('click', function(e) {
                var is_ajax = /edit_ajax|add_ajax/g,
                        is_delete_ajax = /delete_ajax/g,
                        is_delete = /delete\/[0-9]{1,}/g,
                        $href = $(this).attr('href');
                self.url = $href;
                self.isAjax = true;
                $(self.element).data('on-validate', true);
                if (is_ajax.test($href)) {
                    e.preventDefault();

                    var $ajax = self.ajaxLoadForm();
                    $ajax.success(function(data) {
                        var form_html = self.parseFormDataGrid(data);

                        $('#datagrid-box-form').html(form_html);
                    }).then(function() {
                        $(".form-add-edit form").find('.auto_completedatagrid').each(function(i) {
                            var url = $(this).attr('data-url'),
                                    field = $(this).attr('data-field') ? $(this).attr('data-field') : $(this).attr('name');
                            $(this).autocomplete({
                                appendTo: '.form-add-edit',
                                minLength: 1,
                                source: function(request, response) {
                                    $.ajax({
                                        url: url,
                                        data: {
                                            q: extractLast(request.term),
                                            search: request.term
                                        },
                                        type: 'post',
                                        dataType: 'json',
                                        success: function(data) {

                                            response($.map(data, function(item) {
                                                
                                                return {
                                                    label: item[field],
                                                    value: item[field]
                                                };
                                            }));
                                        }
                                    });
                                },
                                search: function() {
                                    
                                    // custom minLength
                                    var term = extractLast(this.value);
                                    if (term.length < 2) {
                                        return false;
                                    }
                                },
                                focus: function() {
                                    // prevent value inserted on focus
                                    return false;
                                },
                                select: function(event, ui) {
                                    var terms = split(this.value);
                                    // remove the current input
                                    
                                    terms.pop();
                                    // add the selected item
                                    terms.push(ui.item.value);
                                    // add placeholder to get the comma-and-space at the end
                                    terms.push("");
                                    this.value = terms.join(", ");
                                    return false;
                                }
                            });

                        });


                    }).done(function() {
                        self.openDialog();

                        //initialize plugins

                        self.options.callbackCompleteForm($("form.form-dialog-datagrid"));

                        $("form.form-dialog-datagrid").validationEngine({
                            ajaxFormValidation: true,
                            ajaxFormValidationMethod: 'post',
                            onBeforeAjaxFormValidation: function() {
                                $('.datagridDialog').append('<span class="i-loading"></span>');

                            },
                            onAjaxFormComplete: function(status, form, json, options) {
                                
                                $('.i-loading').remove();
                                if (status === true) {

                                    if (json.error == false) {
                                        $('#datagrid-box-form').dialog('close');
                                        $('#reset-' + json.key).trigger('click');
                                        $('.message_' + json.key).hide().html(json.message).slideDown().delay(3000).slideUp(500, function() {
                                            $('.message_' + json.key).html('');
                                        });
                                    } else {
                                        var message = json.message != undefined ? json.message : '';
                                        $('.message-response').html(message).slideDown().delay(3000).slideUp();

                                    }

                                    $('a[role="close-message"]').on('click', function() {
                                        $('.message_' + json.key).slideUp(500, function() {
                                            $('.message_' + json.key).html('');
                                        })
                                    });

                                }
                            },
                            promptPosition: 'bottomLeft'
                        });


                        $('.gridOpenManager').bind('click', function() {
                            self.initManagerFiles();
                        });


                        initFileUploadConfig();

                        $('input.datagrid-input-date').datepicker({'dateFormat': 'dd/mm/yy'}).mask('99/99/9999').css({'width': '150px;'});
                        $('input.datagrid-input-datetime').mask('99/99/9999 99:99:99');
                        $('input.datagrid-input-time').mask('99:99:99');
                        $('input.double').css({'width': '150px'});
                        $('label[validate="required"]').append('<strong>*</strong>');

                        $(".form-add-edit form textarea").htmlarea({
                            toolbar: [
                                ["bold", "italic", "underline", 'unorderedList', 'orderedList', 'horizontalrule'],
                                ["h1", "h2", "h3", "h4", "h5", "h6"],
                                ["link", "unlink", 'html']
                            ]
                        });

                    }).fail(function(e, stas) {
                        alert(stas);
                    });



                }
                if (is_delete_ajax.test($href)) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    self.confirmDialog();
                }
                if (is_delete.test($href)) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                    self.isAjax = false;
                    self.confirmDialog();
                }

            });


        },
        failAction: function(ev, status, settings) {
            $('#datagrid-dialog-confirm').html('<div class="alert-box alert">' +
                    'Acesso n&atilde;o permitido'
                    + '</div>');
        }
        ,
        confirmDialog: function() {
            var markup = '<div id="datagrid-dialog-confirm" title="' + this.options.dialogConfirmTitle + '">' +
                    this.options.dialogConfirmText +
                    '<div class="errorResponse"></div>' +
                    +'</div>',
                    config = this.options.dialogConfirm,
                    $bts = this.options.dialogConfirmButtonsText,
                    self = this,
                    $ajax = {};
            $('#datagrid-dialog-confirm').remove();

            var buttons = {}
            buttons[$bts.confirm] = function() {
                var objDialog = this;
                if (self.isAjax) {
                    self.data = {};
                    self.dataType = 'json';
                    $ajax = self.ajaxLoadForm();
                    $ajax.then(function(data) {
                        if (data.error != true) {
                            $(objDialog).dialog('close');
                            $('#reset-' + data.key).trigger('click');
                            $('.message_' + data.key).hide().html(data.message).slideDown().delay(2000).slideUp(500, function() {
                                $(this).html('');
                            });

                        }
                    }); //.error(self.failAction);
                }
                if (!self.isAjax) {
                    window.location = self.url;
                }

            }
            buttons[$bts.cancel] = function() {
                $('#datagrid-dialog-confirm').dialog('close');
            }



            $(markup).appendTo('body').dialog({
                minWidth: '90%',
                minHeight: 150,
                modal: true,
                resizable: false,
                buttons: buttons
            });
        },
        ajaxLoadForm: function() {
            return $.ajax({
                url: this.url,
                data: this.data,
                type: 'post',
                beforeSend: function() {
                    $('.box-actions-add').append('<span id="loadActionsDataGridAjax" class="ajaxLoadinFormBeforeSend"> Carregando formulário ... </span>');
                },
                complete: function() {
                    
                    $('.ajaxLoadinFormBeforeSend').each(function(){
                        $(this).fadeOut(500, function() {
                            $(this).remove();
                         });

                    })

                },
                dataType: this.dataType
            });
        },
        openDialog: function() {
            var self = this;
            $('#datagrid-box-form').dialog({
                width: '95%',
                maxHeight: 500,
                zIndex: 30000,
                dialogClass: 'datagridDialog',
                show: {
                    effect: "easing",
                    duration: 500
                },
                modal: true,
                buttons: [{
                        text: 'Salvar',
                        'class': 'btn btn-primary',
                        click: function() {
                            $('form.form-dialog-datagrid').trigger('submit');
                        }}, {
                        text: 'Cancelar',
                        click: function() {
                            $(this).dialog('close');

                        },
                        'class': 'btn btn-danger'}]

            });


            $('.ui-dialog.ui-widget.ui-widget-content').css({
                top: '100px'
            });
        },
        prepareForm: function() {
            var data = {};
            $('.form-add-edit form').find('input,textarea,select').each(function(e) {
                var name = $(this).attr('name'),
                        $value = $(this).val();
                data[name] = $value;
            });

            this.data = data;


        },
        reloadGrid: function(data) {
            if (data.error != true) {
                $('#datagrid-box-form, #datagrid-dialog-confirm').dialog('close');
                $('#reset-' + data.key).trigger('click');
                $('.message_' + data.key).hide().html(data.message).slideDown();

            }
        },
        parseFormDataGrid: function(data) {
            var $form = data.grid.form, form = '', iform = '';
            $('#form-dialog-datagrid').remove();
            // form = '<h3 class="datagrid-title">'+data.grid.as_title+'</h3>';
            if ($form.inputs != undefined) {
                var $inputs = $form.inputs;
                if ($inputs.length > 0) {
                    form += '<div class="form-container-grid">' +
                            '<div class="col-xs-12 large-12 small-12">' +
                            '<div class="form-add-edit">' +
                            form_open($form.url, 'class="form-dialog-datagrid"');

                    for (var i  in $inputs) {

                        var item = $inputs[i],
                                type = item.db_type,
                                pattern_v = /required/gi,
                                is_validate = item.validate != '' ? 'validate[' + item.validate + ']' : '',
                                is_required = pattern_v.test(is_validate) ? 'required' : '',
                                $maxLength  = item.max_length != false  ? 'maxLength="'+item.max_length+'"' : ''; 
                        switch (type) {
                            case'primary_key':
                            case'hidden':
                                form += form_hidden(item.name, item.value);
                                break;

                            case'varchar':
                            case'int':
                            case'integer':
                            default:

                                form +=
                                        '<div class="row"><div class="form-group box-' + item.name + '">' +
                                        '<div class="small-12 ilabel box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + '  box-field-' + item.name + ' small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control ' + is_validate + '" autocomplete="off"  ' + $maxLength + '') +
                                        '</div>' +
                                        '</div></div>';

                                break;
                            case'auto_complete':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label box-label-' + item.name + '  col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + '  small-12 large-9">' +
                                        form_input(item.name, item.value, 'placeholder="auto complete" class="auto_completedatagrid form-control ' + is_validate + '" ' + item.extra + ' autocomplete="off" ' + $maxLength ) +
                                        '</div>' +
                                        '</div></div>';

                                break;
                            case'password':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-6  col-sm-6 box-field box-field-' + item.name + ' small-12 large-9">' +
                                        form_password(item.name, item.value, 'class="form-control ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'double':
                            case'decimal':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 col-md-2 col-sm-2 box-label  box-label-' + item.name + ' large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + '  small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control double ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'date':


                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 col-md-2 col-sm-2 box-label box-label-' + item.name + ' large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + '  small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control datagrid-input-date ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'datetime':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + '  small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control datagrid-input-datetime ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'time':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + ' small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control datagrid-input-time ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'relation':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + ' small-12 large-9">' +
                                        form_dropdown(item.name, item.options, item.value, ' class="form-control" ' + is_validate + '') +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'custom':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12 box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, '') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + ' small-12 large-9">' +
                                        item.value +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case'tinytext':
                            case'mediumtext':
                            case'text':
                            case'longtext':

                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12  box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 box-field box-field-' + item.name + ' small-12 large-9">' +
                                        form_textarea(item.name, item.value, 'class="form-control ' + is_validate + '"  rows="6" ' + $maxLength +' autocomplete="off"') +
                                        '</div>' +
                                        '</div></div>';
                                break;

                            case 'file':
                                form +=
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12  box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 file-box-input box-field box-field-' + item.name + ' small-12 large-9">' +
                                        form_input(item.name, item.value, 'class="form-control ' + is_validate + '" autocomplete="off" ' + $maxLength) +
                                        '<a href="#open" class="gridOpenManager button btn btn-danger btn-sm tiny alert">Abrir</a>' +
                                        '</div>' +
                                        '</div></div>';
                                break;
                            case 'upload':

                                form += form_hidden(item.name, item.value, 'class="form-control iupload autocomplete="off"  ' + $maxLength);
                                iform =
                                        '<div class="row"><div class="form-group">' +
                                        '<div class="small-12  box-label box-label-' + item.name + ' col-md-2 col-sm-2 large-3 box-filed box-input-' + item.name + '">' +
                                        form_label(item.label, item.label, 'validate="' + is_required + '"') +
                                        '</div>' +
                                        '<div class="col-md-9  col-sm-9 upload-box-input box-field box-field-' + item.name + ' small-12 large-9">' +
                                        '<form data-name="' + item.name + '" action="' + item.extra + '" method="post" id="iupload" enctype="multipart/form-data">' +
                                        '<div id="drop">' +
                                        'Arraste <br/>' +
                                        '<a>Arquivo</a>' +
                                        '<input type="file" name="upl" multiple />' +
                                        '<ul></ul>' +
                                        '</div>' +
                                     '</form>' +
                                        '</div>' +
                                        '</div></div>';
                                break;

                        }



                    }


                    form += '<div class="message-response alert-box alert" style="display:none;"></div>';
                    form += '</form>' +
                            iform +
                            '</div>' +
                            '</div>' +
                            '</div>';

                }


            }


            return form;

        },
        initManagerFiles: function() {
            var sizeofBox = $('.gridBoxManager').remove();
            $('body').append('<div class="gridBoxManager"><div id="managerFinder"></div></div>')

            $('.gridBoxManager').dialog({
                width: '80%',
                height: 500,
                modal: true,
                zIndex: 10000
            });


            $('#managerFinder').elfinder({
                url: this.options.urlFile, // connector URL (REQUIRED)
                lang: 'pt_BR'             // language (OPTIONAL)
            }).elfinder('instance');

        }
    };

    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    }






})(jQuery, window, document);


function initFileUploadConfig() {

    var ul = $('#iupload ul'), index = 1, tpl = '', exist_form = $('#iupload').size();

    if (exist_form > 0) {
        $('#drop a').click(function() {
            // Simulate a click on the file input button
            // to show the file browser dialog
            $(this).parent().find('input').click();
        });
        name = $('#iupload').attr('data-name');
        items = $('input[name="' + name + '"').val();


        items = split(items);

        for (var i = 0, max = items.length; i < max; i += 1) {
            var ifile = items[i];
            if (ifile != '') {
                tpl = $('<li  data-index="' + index + '" class="working"><input type="text" value="0" data-width="30" data-height="30"' +
                        ' data-fgColor="#f9b815" data-readOnly="1" data-bgColor="#3e4043" /><p><img  src="' + url_base + 'public/images/' + ifile + '" width="60px;" name="' + ifile + '"/> <label>' + ifile + '<br/><i></i></label></p><span data-index="' + index + '"></span></li>');

                tpl.appendTo(ul);
                index += 1;
            }

        }
        initRemoveItemsUpload();





        // Initialize the jQuery File Upload plugin
        $('#iupload').fileupload({
            dataType: 'json',
            // This element will accept file drag/drop uploading
            dropZone: $('#drop'),
            // This function is called when a file is added to the queue;
            // either via the browse button, or via drag/drop:
            add: function(e, data) {

                tpl = $('<li  data-index="' + index + '" class="working"><input type="text" value="0" data-width="30" data-height="30"' +
                        ' data-fgColor="#f9b815" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span  data-index="' + index + '"></span></li>');

                // Append the file name and file size
                /*
                 tpl.find('p').html('<span>'+data.files[0].name+'<')
                 .append('<i>' + formatFileSize(data.files[0].size) + '</i>');
                 */
                // Add the HTML to the UL element
                data.context = tpl.appendTo(ul);

                // Initialize the knob plugin
                tpl.find('input').knob();

                // Listen for clicks on the cancel icon
                initRemoveItemsUpload();

                // Automatically upload the file once it is added to the queue
                var jqXHR = data.submit();
            },
            done: function(e, data) {
                var ifl = [],
                        iname = $(this).attr('data-name'),
                        ithis = $('input[name="' + iname + '"]'),
                        items = split(ithis.val());

                $.each(data.result, function() {
                    if (this.name) {
                        $('li[data-index="' + index + '"]').find('p').html('<img  src="' + url_base + 'public/images/' + this.name + '" width="60px;"/> <label>' + this.name + '<br/><i>' + this.size + '</i></label>');
                        items.push(this.name);
                    }



                });

                if (data.result.error === true) {
                    
                    $('li[data-index="' + index + '"]').html(data.result.message);
                }


                items = items.join(',');
                ithis.val(items);

                index += 1;
            },
            progress: function(e, data) {

                // Calculate the completion percentage of the upload
                var progress = parseInt(data.loaded / data.total * 100, 10);

                // Update the hidden input field and trigger a change
                // so that the jQuery knob plugin knows to update the dial
                data.context.find('input').val(progress).change();

                if (progress == 100) {
                    data.context.removeClass('working');
                }
            },
            fail: function(e, data) {
                // Something has gone wrong!
                data.context.addClass('error');
            }

        });


        // Prevent the default action when a file is dropped on the window
        $(document).on('drop dragover', function(e) {
            e.preventDefault();
        });
    }
    // Helper function that formats the file sizes


}


function initRemoveItemsUpload() {
    var tpl = $('#iupload ul li');
    tpl.find('span').click(function() {
        var i_index = $(this).attr('data-index'),
                img = $('#iupload ul li[data-index="' + i_index + '"]').find('img').attr('name'),
                $ajax = delete_file(img);


        $ajax.then(function(data) {
            if (data.error == false) {
                $('#iupload ul li[data-index="' + i_index + '"]').fadeOut(function() {
                    $(this).remove();
                    console.log(name);
                    var items = split($('input[name="' + name + '"]').val());
                    var imgs = delete_items_array(items, img);
                    $('input[name="' + name + '"]').val(imgs.join(','));

                });
            }
        });


        /*
         $('#iupload ul li[data-index="'+i_index+'"]').fadeOut(function(){
         
         $(this).remove();
         });*/

    });
}

function delete_file(img) {
    return  $.ajax({
        url: url_site + 'upload_delete_img',
        type: 'post',
        dataType: 'json',
        data: {file_delete: img}
    });

}

function delete_items_array(array, item) {
    var arrays = [];

    if (Object.prototype.toString.call(array) != '[object Array]' && typeof array == 'String') {
        arrays.push(array);
    }
    for (var i = 0, max = array.length; i < max; i += 1) {
        var rm = array[i];
        if (rm != item) {
            arrays.push(rm);
        }

    }

    return arrays;

}
function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }

    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2) + ' GB';
    }

    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
    }

    return (bytes / 1000).toFixed(2) + ' KB';
}



function split(val) {
    pattern = /,/gi;
    if (pattern.test(val)) {
        return val.split(/,/gi);
    }
    if (val != '') {

        return new Array(val);
    }
    return [];



}
function extractLast(term) {
    return split(term).pop();
}